﻿import { Router } from '@angular/router';
import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ConfigStateService, LocalizationService } from '@abp/ng.core';
import { EditState } from 'joy-abpui-angular';
import { UniqueCodeSettingComponent } from '../../core/unique-code-setting/unique-code-setting.component';
import { {{class_name}}Dto, {{class_name}}Service } from '../../proxy/joy/erp/{{to_kebab_case(project_group_name)}}/{{to_kebab_case(parent_menu)}}';

@Component({
  selector: 'lib-{{to_kebab_case(class_name)}}-daw-entity',
  templateUrl: './{{to_kebab_case(class_name)}}-daw-entity.component.html',
  styleUrls: ['./{{to_kebab_case(class_name)}}-daw-entity.component.less'],
})
export class {{class_name}}DawEntityComponent implements OnInit {
  entityConfig = {
    defaultValue: {
    },
  };

  @Input() id?: string;

  editState: EditState;
  validateForm: FormGroup;
  currentEntity: {{class_name}}Dto;

  get codeInputDisabled() {
    var uniqueCodeConfigration = this.config.getSetting("UniqueCodeConfigration:{{namespace}}.{{class_name}}");
    var uniqueCodeConfigrationObj = JSON.parse(uniqueCodeConfigration);
    return uniqueCodeConfigrationObj["AutoCode"];
  }

  constructor(
    public router: Router,
    public fb: FormBuilder,
    public config: ConfigStateService,
    public message: NzMessageService,
    public modal: NzModalService,
    public modalService: NzModalService,
    public localizationService: LocalizationService,
    public entityService: {{class_name}}Service,
  ) {}

  ngOnInit(): void {
    this.editState = EditState.Empty;
    this.currentEntity = this.entityConfig.defaultValue as {{class_name}}Dto;
    this.validateForm = this.fb.group({
      code: [this.entityConfig.defaultValue['code']],
      {{~ for property in exclude_propertys(self_value_propertys, "TenantId", "Level", "ParentId") ~}}
      {{to_camel_case(property.name)}}: [this.entityConfig.defaultValue['{{to_camel_case(property.name)}}']],
      {{~ end ~}}
    });

    if (this.id) {
      this.entityService.get(this.id).subscribe(entity => {
        if (entity) {
          this.setCurrentEntity(entity);
        }
      });
    }

    this.validateForm.valueChanges.subscribe(_ => {
      if (this.editState == EditState.Empty) {
        this.editState = EditState.Creating;
      } else if (this.editState == EditState.View) {
        this.editState = EditState.Editing;
      }
    });
  }

  save() {
    if (this.editState == EditState.Creating) {
      this.entityService
        .create({ ...this.validateForm.value })
        .subscribe(entity => {
          if (!!entity) {
            this.setCurrentEntity(entity);
            this.message.success(this.l('BasicArchives::UI:Message.AddSuccess'));
          }
        });
    } else if (this.editState == EditState.Editing) {
      this.entityService
        .update(this.currentEntity.id, {
          ...this.currentEntity,
          ...this.validateForm.value
        })
        .subscribe(entity => {
          if (!!entity) {
            this.setCurrentEntity(entity);
            this.message.success(this.l('BasicArchives::UI:Message.EditSuccess'));
          }
        });
    }
  }

  giveup() {
    this.giveUpConfirm().then(_ => {
      if (this.editState == EditState.Creating) {
        //表单状态为创建时，清空数据
        this.changeToEmpty();
      } else if (this.editState == EditState.Editing) {
        //表单状态为编辑时，恢复原数据
        this.setCurrentEntity(this.currentEntity);
      }
    });
  }

  new() {
    this.checkDirty().then(_ => this.changeToEmpty());
  }

  copy() {
    this.checkDirty().then(_ => {
      this.setCurrentEntity({...this.currentEntity, code: ""});
      this.currentEntity = this.entityConfig.defaultValue as {{class_name}}Dto;
      this.editState = EditState.Creating;
    });
  }

  delete() {
    this.modal.confirm({
      nzTitle: this.l('BasicArchives::UI:Confirm.Title.Tips'),
      nzContent: this.l('BasicArchives::UI:Confirm.Content.DeleteConfirm'),
      nzOkText: this.l('BasicArchives::UI:Confirm.Button.OK'),
      nzCancelText: this.l('BasicArchives::UI:Confirm.Button.Cancel'),
      nzOnOk: () => {
        this.entityService.delete(this.currentEntity.id).subscribe(_ => this.changeToEmpty());
      },
    });
  }

  refresh() {    
    if(this.currentEntity.id) {
      this.entityService.get(this.currentEntity.id).subscribe(entity => {
        if (!!entity) {
          this.setCurrentEntity(entity);
        }
      });
    } else {      
      this.changeToEmpty();
    }
  }

  search(code) {
    this.entityService.find(code).subscribe(entity => {
      if (!!entity) {
        this.setCurrentEntity(entity);
      } else {
        this.message.warning(this.l('BasicArchives::UI:Message.CanNotFund', this.l('BasicArchives::Menu:{{project_group_name}}.{{parent_menu}}.{{class_name}}'), code));
      }
    });
  }

  uniqueCodeSetting() {
    const modalRef = this.modal.create({
      nzTitle: this.l('BasicArchives::UI:UniqueCodeSetting.Title'),
      nzContent: UniqueCodeSettingComponent,
      nzWidth: 800,
      nzComponentParams: {
        settingKey: 'UniqueCodeConfigration:{{namespace}}.{{class_name}}'
      },
      nzFooter: null,
      nzClosable: true,
      nzMaskClosable: false
    });

    modalRef.afterClose.subscribe(result => {
      if (result) {
        this.refresh();
      }
    });
  }

  protected changeToEmpty() {
    this.validateForm.reset(this.entityConfig.defaultValue, { emitEvent: false });
    this.editState = EditState.Empty;
  }

  protected setCurrentEntity(entity: {{class_name}}Dto) {
    this.currentEntity = entity;
    this.validateForm.reset(this.currentEntity, { emitEvent: false });
    this.editState = EditState.View;
  }

  protected giveUpConfirm(): Promise<any> {
    return new Promise((resolve, reject) => {
      if (this.editState != EditState.Creating && this.editState != EditState.Editing)
        return reject();
      this.modal.confirm({
        nzTitle: this.l('BasicArchives::UI:Confirm.Title.Tips'),
        nzContent: this.l('BasicArchives::UI:Confirm.Content.GiveUpConfirm'),
        nzOkText: this.l('BasicArchives::UI:Confirm.Button.OK'),
        nzCancelText: this.l('BasicArchives::UI:Confirm.Button.Cancel'),
        nzOnOk: () => resolve(null),
      });
    });
  }

  protected checkDirty(): Promise<any> {
    return new Promise(resolve => {
      if (this.editState == EditState.Creating || this.editState == EditState.Editing) {
        this.modal.confirm({
          nzTitle: this.l('BasicArchives::UI:Confirm.Title.Tips'),
          nzContent: this.l('BasicArchives::UI:Confirm.Content.ChangeStateConfirm'),
          nzOkText: this.l('BasicArchives::UI:Confirm.Button.OK'),
          nzCancelText: this.l('BasicArchives::UI:Confirm.Button.Cancel'),
          nzOnOk: () => resolve(null),
        });
      } else {
        resolve(null);
      }
    });
  }

  protected l(key: string, ...args: any[]): string {
    return this.localizationService.instant(key, ...args);
  }
}
